import axios from 'axios';
import { getToken } from './auth';

// 创建axios实例
const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 添加请求拦截器，自动附加token
api.interceptors.request.use(
  config => {
    // 获取token
    const token = getToken();
    // 如果有token则添加到请求头
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 获取课程列表（分页）
export const getCourses = async (pageNum = 1, pageSize = 10) => {
  try {
    const response = await api.get('/courses/getCourseList', {
      params: { pageNum, pageSize }
    });
    if (response.data && response.data.code === 200) {
      return response.data.data;
    } else {
      console.error('获取课程列表失败:', response.data.message);
      return { pageNum, pageSize, total: 0, courseList: [] };
    }
  } catch (error) {
    console.error('获取课程列表请求失败:', error);
    return { pageNum, pageSize, total: 0, courseList: [] };
  }
};

// 获取管理端课程列表（分页）
export const getCoursesManage = async (pageNum = 1, pageSize = 10) => {
  try {
    const response = await api.get('/manage/getCourseList', {
      params: { pageNum, pageSize }
    });
    if (response.data && response.data.code === 200) {
      return response.data.data;
    } else {
      console.error('获取课程列表失败:', response.data.message);
      return { pageNum, pageSize, total: 0, courseList: [] };
    }
  } catch (error) {
    console.error('获取课程列表请求失败:', error);
    return { pageNum, pageSize, total: 0, courseList: [] };
  }
};

// 上传课程封面图片
export const uploadCourseImage = async (file) => {
  try {
    const formData = new FormData();
    formData.append('file', file);
    
    // 修改请求头，不设置Content-Type，让浏览器自动设置
    const config = {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    };
    
    const response = await api.post('/manage/uploadImg', formData, config);
    if (response.data && response.data.code === 200) {
      return response.data.data;
    } else {
      throw new Error(response.data.message || '上传失败');
    }
  } catch (error) {
    console.error('上传图片失败:', error);
    throw error;
  }
};

// 获取上传签名URL
export const getUploadSignUrl = async (params) => {
  try {
    const response = await api.get('/manage/getUploadSignUrl', { params });
    if (response.data && response.data.code === 200) {
      return response.data.data;
    } else {
      throw new Error(response.data.message || '获取上传签名失败');
    }
  } catch (error) {
    console.error('获取上传签名失败:', error);
    throw error;
  }
};

// 直接上传视频到OSS
export const uploadVideoToOSS = async (signedUrl, file, onProgress) => {
  return new Promise((resolve, reject) => {
    try {
      const xhr = new XMLHttpRequest();
      
      // 设置进度监听
      xhr.upload.onprogress = (event) => {
        if (event.lengthComputable && onProgress) {
          const percentComplete = Math.round((event.loaded / event.total) * 100);
          onProgress(percentComplete);
        }
      };
      
      // 设置完成回调
      xhr.onload = () => {
        if (xhr.status >= 200 && xhr.status < 300) {
          // 成功上传，返回不带查询参数的URL
          const videoUrl = signedUrl.split('?')[0];
          resolve(videoUrl);
        } else {
          const errorMsg = `上传失败，状态码: ${xhr.status}, 响应: ${xhr.responseText}`;
          console.error(errorMsg);
          reject(new Error(errorMsg));
        }
      };
      
      // 设置错误回调
      xhr.onerror = () => {
        const errorMsg = '网络错误，可能是CORS问题，请检查OSS配置';
        console.error(errorMsg);
        reject(new Error(errorMsg));
      };
      
      // 设置超时回调
      xhr.ontimeout = () => {
        reject(new Error('上传超时'));
      };
      
      // 打开连接 - 使用PUT方法上传到OSS
      xhr.open('PUT', signedUrl, true);
      
      // 关键：设置CORS相关选项
      xhr.withCredentials = false; // 不发送凭证
      
      // 设置Content-Type头，但不添加其他自定义头
      xhr.setRequestHeader('Content-Type', file.type);
      
      // 发送文件
      xhr.send(file);
    } catch (error) {
      console.error('上传过程中发生错误:', error);
      reject(error);
    }
  });
};

// 获取课程详情
export const getCourseById = async (id) => {
  try {
    // 实际项目中应该调用真实API
    const response = await api.get(`/courses/${id}`);
    if (response.data && response.data.code === 200) {
      return response.data.data;
    } else {
      console.error(`获取课程ID=${id}的详情失败:`, response.data.message);
      return null;
    }
  } catch (error) {
    console.error(`获取课程ID=${id}的详情失败:`, error);
    return null;
  }
};

// 删除课程
export const deleteCourse = async (id) => {
  try {
    const response = await api.post('/manage/deleteCourse', { id });
    if (response.data && response.data.code === 200) {
      return true;
    } else {
      console.error('删除课程失败:', response.data.message);
      return false;
    }
  } catch (error) {
    console.error('删除课程请求失败:', error);
    return false;
  }
};

// 新增课程
export const addCourse = async (courseData) => {
  try {
    const response = await api.post('/manage/addCourse', courseData);
    if (response.data && response.data.code === 200) {
      return {
        success: true,
        data: response.data.data
      };
    } else {
      console.error('新增课程失败:', response.data.message);
      return {
        success: false,
        message: response.data.message || '新增课程失败'
      };
    }
  } catch (error) {
    console.error('新增课程请求失败:', error);
    return {
      success: false,
      message: error.message || '网络错误，请稍后重试'
    };
  }
};

// 更新课程
export const updateCourse = async (courseData) => {
  try {
    const response = await api.post('/manage/updateCourse', courseData);
    if (response.data && response.data.code === 200) {
      return {
        success: true,
        data: response.data.data
      };
    } else {
      console.error('更新课程失败:', response.data.message);
      return {
        success: false,
        message: response.data.message || '更新课程失败'
      };
    }
  } catch (error) {
    console.error('更新课程请求失败:', error);
    return {
      success: false,
      message: error.message || '网络错误，请稍后重试'
    };
  }
};

export default api;